<template>
  <a-modal
    :open="open"
    width="640px"
    :title="props.rowData?.id ? '修改中药用法' : '新增中药用法'"
    :ok-button-props="{ disabled: !isCompleted }"
    ok-text="保存"
    centered
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="form-style-flex">
      <a-form-item label="用法" class="w-full" v-bind="validateInfos.yf">
        <a-input v-model:value="formState.yf" placeholder="请输入" @blur="onChangeEmpName" />
      </a-form-item>
      <a-form-item label="助记码" class="w-1/2" v-bind="validateInfos.zjm">
        <a-input v-model:value="formState.zjm" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="顺序号" class="w-1/2" v-bind="validateInfos.outorder">
        <a-input v-model:value="formState.outorder" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="备注" class="w-full">
        <a-textarea v-model:value="formState.memo" :rows="5" placeholder="请输入" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'

const emit = defineEmits(['update:open', 'confirm', 'success'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const formState = ref({
  yf: '',
  zjm: '',
  outorder: '',
  remarks: ''
})
const rulesState = ref({
  yf: [{ required: true, message: '请输入用法' }],
  outorder: [{ required: true, message: '请输入顺序号' }],
  zjm: [{ required: true, message: '请输入助记码' }]
})
const { isCompleted, resetFields, validateInfos } = useForm(formState, rulesState)

const onOk = async () => {
  const res = await post('/operation/opex/doSaveTcmDictYfInfo', formState.value)
  res.code !== 0 ? message.error(res.msg || '操作失败') : message.success('保存成功')
  emit('success')
  onCancel()
}
const onChangeEmpName = async (e) => {
  const { data, code, msg } = await post('/common/util/getPinyin', {
    name: e.target.value
  })
  if (code !== 0) return message.error(msg)
  formState.value.zjm = data
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      formState.value = { ...props.rowData }
    }
  },
  {
    immediate: true
  }
)
const onCancel = () => {
  resetFields()
  emit('update:open', false)
}
</script>
